function clearTimer(timer: any) {
  if (typeof timer !== null) clearTimeout(timer);
  return null;
}

export function debounce(func: any, wait = 600, flag = true) {
  if (typeof func !== "function") throw new TypeError("func必须是一个函数");
  let timer: any = null;
  return function handle(this: typeof handle, ...args: any) {
    let beforeRun = !timer && flag;
    timer = clearTimer(timer);
    timer = setTimeout(() => {
      timer = clearTimer(timer);
      if(!flag) {
        func.apply(this, args);
      }
    }, wait);
    if(beforeRun) {
      func.apply(this, args);
    }
  };
}
